const userStore = require('../../stores/userStore')
Page({

  data: {
    showBack: false,
    studentForm: {
      answer01: '',
      answer02: '',
      answer03: '',
      answer1: '',
      answer2: '',
      answer3: '',
      answer4: ''
    },

    studentForm1: {
      liveWith: '',
      seeParents: '',
      frequencyParents: '',
      livingStandard: '',  
      stay: '',
      familyType: '',
      fatherEdu: '',
      motherEdu: '',
      familyJob: '',
      motherJob: '',
      address: '',
      borthers: '',
      work: '',
      sex: '',
      studentId: '',
      birth: '',
      // id: User.id,
    },

    answer1Options: ['父亲', '母亲', '爷爷（外公）', '奶奶（外婆）', '兄弟姐妹', '其他人'],
      answer2Options: [
        '几乎每天都见',
        '一周好几天见到',
        '一周一两次',
        '一个月一两次',
        '半年一次',
        '一年或几年一次'
      ],
      answer3Options: ['几乎每天', '经常', '偶尔', '很少', '几乎不怎么联系'],
      answer4Options: ['贫困', '不太富裕', '一般', '比较富裕', '很富裕'],
      answer02Options: ['男', '女'],
      answer03Options: ['贫困', '不太富裕', '一般', '比较富裕', '很富裕'],

      idOptions: [''],
      liveWithOptions: ['父亲', '母亲', '爷爷（外公）', '奶奶（外婆）', '兄弟姐妹', '其他人'],
      seeParentsOptions: [
        '几乎每天都见',
        '一周好几天见到',
        '一周一两次',
        '一个月一两次',
        '半年一次',
        '一年一次'
      ],
      frequencyParentsOptions: ['几乎每天', '经常', '偶尔', '很少', '几乎不怎么联系'],
      livingStandardOptions: ['贫困', '不太富裕', '一般', '比较富裕', '很富裕'],
      stayOptions: ['是', '否'],
      familyTypeOptions: ['双亲家庭', '单亲家庭', '重组家庭', '其他'],
      fatherEduOptions: [
        '小学或者小学以下',
        '初中（含初中未毕业）',
        '高中或中专（含高中未毕业）',
        '大专（含夜大、电大）',
        '大学本科',
        '研究生（硕士或博士）'
      ],
      motherEduOptions: [
        '小学或者小学以下',
        '初中（含初中未毕业）',
        '高中或中专（含高中未毕业）',
        '大专（含夜大、电大）',
        '大学本科',
        '研究生（硕士或博士）'
      ],
      familyJobOptions: [
        '城镇无业、失业、半失业者',
        '农业劳动者',
        '产业工人',
        '商业服务业员工',
        '个体工商户',
        '办事人员',
        '专业技术人员',
        '私营企业主',
        '经理人员',
        '国家与社会管理者'
      ],
      motherJobOptions: [
        '城镇无业、失业、半失业者',
        '农业劳动者',
        '产业工人',
        '商业服务业员工',
        '个体工商户',
        '办事人员',
        '专业技术人员',
        '私营企业主',
        '经理人员',
        '国家与社会管理者'
      ],
      addressOptions: ['农村', '乡镇府所在地', '县城', '大城市'],
      borthersOptions: ['没有', '有1个', '>=三个'],
      workOptions: ['父母都在外地工作', '父亲或者母亲在外地工作', '都在本地工作'],
      sexOptions: ['男生', '女生'],
      studentIdOptions: [''],

      test: {
        id: 1,
        liveWith: '你目前主要和一起生活（可多选)',
        seeParents: '你和父母多久见面一次',
        frequencyParents: '你主动和父母联系（微信或电话）的频率',
        livingStandard: '家庭生活水平'
      },
  },

    //完善学生信息上传学生填的数据
    async uploadStudentData (params){
      const app = getApp(); //获取小程序实例
      const token = app.globalData.accessToken||'';//直接从全局数据中获取token
      console.log("token==",token)
      const headers = {
        'content-type': 'application/json',
        'token': token
      };
      
      // return new Promise((resolve,reject) => {
      //   wx.request({
      //     url: 'http://202.192.19.106:8080/api/v2/region/information/save',
      //     method: 'POST',
      //     data:params,
      //     header: headers,

      //     success: (res) => {
      //       resolve(res.data) // 确保返回的数据是API响应的data部分
      //     },
      //     fail: (error) => {
      //       console.error('学生信息上传失败',error)
      //       wx.showToast({
      //         title: '学生信息上传失败，请稍后重试',
      //         duration: 2000
      //       })
      //       reject(error)
      //     }
      //   })
      // })
      try {
        await wx.request({
          url: 'http://202.192.19.106:8080/api/v2/region/information/save',
          method: 'POST',
          data: params,
          header: headers,

          success:function(res)
          {
            console.log("res=",res)
          },
          fail:function(err)
          {
            console.log("err=",err)
          }
        })
      } 
      catch(error)
      {
        console.log("error=",error)
      }
    },
    validate: function() {
      const studentForm1 = this.data.studentForm1
      console.log(studentForm1)
      for (let key in studentForm1) {
        if (studentForm1.hasOwnProperty(key)) {
          let value = studentForm1[key]
          console.log(value)
          if (!value|| value.trim() === '') {
            return false
          }
        }
      }
      console.log(1)
      return true
    },
    showToastAndJump:function() {
      wx.showToast({
        title: '表单提交成功！',
        icon:'success',
        duration: 2000
      });
      // 使用setTimeout来延迟执行jumpToHome函数
      setTimeout(() => {
          this.jumpToHome();
      }, 2000);
    },
    submitForm: function() {
      if (this.validate())
      {
        this.sendData()
        const studentForm1 = this.data.studentForm1
        console.log("studentForm1=",studentForm1)
        this.uploadStudentData(studentForm1)
        // const response = this.uploadStudentData(this.data.studentForm1)
        // const response = userStore.uploadStudentData(this.setData.studentForm1)
        // console.log(response)
        // wx.showToast({
        //   title: '表单提交成功！',
        //   icon:'success',
        //   duration: 2000
        // }).then(() => {
        //   this.jumpToHome()
        // })
        this.showToastAndJump()
        wx.setStorageSync('hasSeenOverlay', true)
        // this.showBack = true
        this.setData({
          showBack: true
        })
        // this.jumpToHome()
      } else {
        wx.showToast({
          title: '请完善表单信息！',
          icon:'error',
          duration:2000
        })
      }
    }, 
    // validate: function() {
    //   return new Promise((resolve) => {
    //     const query = wx.createSelectorQuery().in(this);
    //     query.select('.form-item input, .form-item picker').nodes((res) => {
    //       const formControls = res.nodes;
    //       let allValid = true;
    //       formControls.forEach(control => {
    //         if (control.tagName === 'INPUT') {
    //           if (!control.value) {
    //             allValid = false;
    //           }
    //         } else if (control.tagName === 'PICKER') {
    //           if (!control.value) {
    //             allValid = false;
    //           }
    //         }
    //       });
    //       resolve(allValid);
    //     }).exec();
    //   });
    // },   
    // validate: function() {
    //   const formItems = this.selectComponents('.form-item')
  
    //   for (const item of formItems) {
    //     const formControls = item.selectQuery('input, picker').selectNodes().nodes
    //     for (const control of formControls) {
    //       if (control.tagName === 'INPUT') {
    //         if(!control.value) {
    //           return false
    //         }
    //       } else if (control.tagName === 'PICKER') {
    //         if (!control.value) {
    //           return false;
    //         }
    //       }
    //     }
    //   }
    //   return true
    // },
    resetForm: function() {
      this.setData({
        studentForm1: {
          // id: User.id,
          liveWith: '',
          seeParents: '',
          frequencyParents: '',
          livingStandard: '',
          stay: '',
          familyType: '',
          fatherEdu: '',
          motherEdu: '',
          familyJob: '',
          motherJob: '',
          address: '',
          borthers: '',
          work: '',
          sex: '',
          studentId: '',
          birth: ''
        },
      })
    },

    onSexChange: function(e) {
      const index = e.detail.value;
      this.setData({
        'studentForm1.sex': this.data.sexOptions[index]
      });
    },
  
    onBirthChange: function(e) {
      this.setData({
        'studentForm1.birth': e.detail.value
      })
    },
  
    onStudentIdChange: function(e) {
      this.setData({
        'studentForm1.studentId': e.detail.value
      })
    },
  
    onAddressChange: function(e) {
      const index = e.detail.value;
      this.setData({
        'studentForm1.address': this.data.addressOptions[index]
      });
    },
  
    onBorthersChange: function(e) {
      const index = e.detail.value;
      this.setData({
        'studentForm1.borthers': this.data.borthersOptions[index]
      });
    },
  
    onFamilyTypeChange: function(e) {
      const index = e.detail.value;
      this.setData({
        'studentForm1.familyType': this.data.familyTypeOptions[index]
      });
    },
  
    onWorkChange: function(e) {
      const index = e.detail.value;
      this.setData({
        'studentForm1.work': this.data.workOptions[index]
      });
    },
  
    onLiveWithChange: function(e) {
      const index = e.detail.value;
      const oldvalue = this.data.studentForm1.liveWith
      this.setData({
        'studentForm1.liveWith': oldvalue + ' ' + this.data.liveWithOptions[index] 
      });
    },
  
    onStayChange: function(e) {
      const index = e.detail.value;
      this.setData({
        'studentForm1.stay': this.data.stayOptions[index]
      });
    },
  
    onSeeParentsChange: function(e) {
      const index = e.detail.value;
      this.setData({
        'studentForm1.seeParents': this.data.seeParentsOptions[index]
      });
    },
  
    onFrequencyParentsChange: function(e) {
      const index = e.detail.value;
      this.setData({
        'studentForm1.frequencyParents': this.data.frequencyParentsOptions[index]
      });
    },
  
    onFatherEduChange: function(e) {
      const index = e.detail.value;
      this.setData({
        'studentForm1.fatherEdu': this.data.fatherEduOptions[index]
      });
    },
  
    onMotherEduChange: function(e) {
      const index = e.detail.value;
      this.setData({
        'studentForm1.motherEdu': this.data.motherEduOptions[index]
      });
    },
  
    onFamilyJobChange: function(e) {
      const index = e.detail.value;
      this.setData({
        'studentForm1.familyJob': this.data.familyJobOptions[index]
      });
    },
  
    onMotherJobChange: function(e) {
      const index = e.detail.value;
      this.setData({
        'studentForm1.motherJob': this.data.motherJobOptions[index]
      });
    },
  
    onLivingStandardChange: function(e) {
      const index = e.detail.value;
      this.setData({
        'studentForm1.livingStandard': this.data.livingStandardOptions[index]
      });
    },
    // 跳到主页面
    jumpToHome: function() {
      return new Promise((resolve,reject) => {
        wx.navigateTo({
          url: '/pages/index/index',
          success: function() {
            resolve(true)
          },
          fail: function(error) {
            console.error('导航失败',error)
            reject(false)
          }
        })
      })
    },
  
    sendData: function() {
      // 将 liveWithOptions 数组转换为字符串，使用逗号作为分隔符
      const liveWithOptionsString = this.data.liveWithOptions.join(',')
      console.log("liveWithOPtions=",liveWithOptionsString)
      // 使用 setData 方法更新数据，触发视图更新
      // this.setData({
      //   studentForm1: {
      //     liveWith: liveWithOptionsString
      //   }
      // })
      this.setData({
        'studentForm1.liveWith': liveWithOptionsString
      });
    },
  
})